<template>
    <div class="app-container ios-style-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="订单号" prop="orderNo">
                <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="订单标题" prop="orderTitle">
                <el-input v-model="queryParams.orderTitle" placeholder="请输入订单标题" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="是否加急" prop="isUrgent">
        <el-select v-model="queryParams.isUrgent" placeholder="请选择是否加急" clearable>
          <el-option v-for="dict in isUrgentOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->

            <el-form-item label="关键词" prop="keyword">
                <el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>

            <el-form-item label="程序类型" prop="techType">
                <el-select v-model="queryParams.techType" placeholder="请选择程序类型" clearable>
                    <el-option v-for="dict in techTypeOptions" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="截止时间">
                <el-date-picker v-model="daterangeEstimatedEndTime" style="width: 240px" value-format="yyyy-MM-dd"
                    type="daterange" range-separator="-" start-placeholder="开始日期"
                    end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                    v-hasPermi="['dashboard:grab:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-share" size="mini"
                    @click="handleSharePage">分享当前页</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['dashboard:grab:edit']">编辑</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                    @click="handleDelete" v-hasPermi="['dashboard:grab:remove']">删除</el-button>
            </el-col> -->
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                    v-hasPermi="['dashboard:grab:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="订单号" align="center" prop="orderNo" />
            <el-table-column label="订单标题" align="center" prop="orderTitle" width="200" :show-overflow-tooltip="true" />
            <el-table-column label="订单简介" align="center" prop="introduce" width="300" :show-overflow-tooltip="true" />
            <el-table-column label="任务类型" align="center" prop="orderTaskName" />
            <el-table-column label="程序类型" align="center" prop="techType" />
            <el-table-column label="截止时间" align="center" prop="estimatedEndTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.estimatedEndTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="信用分" align="center" prop="requiredCreditScore" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-s-claim"
                        @click="handlePreempt(scope.row)">抢单</el-button>
                    <el-button size="mini" type="text" icon="el-icon-upload"
                        @click="handleFiles(scope.row)">查看文件</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改订单主表对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="订单号" prop="orderNo">
                            <el-input v-model="form.orderNo" placeholder="请输入订单号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单标题" prop="orderTitle">
                            <el-input v-model="form.orderTitle" placeholder="请输入订单标题" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户姓名" prop="customerName">
                            <el-input v-model="form.customerName" placeholder="请输入客户姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户电话" prop="customerPhone">
                            <el-input v-model="form.customerPhone" placeholder="请输入客户联系方式" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否加急" prop="isUrgent">
                            <el-select v-model="form.isUrgent" placeholder="请选择是否加急">
                                <el-option v-for="dict in isUrgentOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="程序类型" prop="techType">
                            <el-input v-model="form.techType" placeholder="请输入程序类型（SpringBoot+Vue3）" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="开始时间" prop="startTime">
                            <el-date-picker clearable v-model="form.startTime" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择程序开始时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="截止时间" prop="estimatedEndTime">
                            <el-date-picker clearable v-model="form.estimatedEndTime" type="date"
                                value-format="yyyy-MM-dd" placeholder="请选择截止时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="订单金额" prop="rewardAmount">
                            <el-input v-model="form.rewardAmount" placeholder="请输入订单金额" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="订单加价" prop="raiseAmount">
                            <el-input v-model="form.raiseAmount" placeholder="请输入订单加价" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="订单状态" prop="orderStatus">
                            <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
                                <el-option v-for="dict in orderStatusOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="收款状态" prop="orderStatusAmount">
                            <el-select v-model="form.orderStatusAmount" placeholder="请选择订单收款状态">
                                <el-option v-for="dict in orderStatusAmountOptions" :key="dict.value"
                                    :label="dict.label" :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="售中姓名" prop="inSaleName">
                            <el-input v-model="form.inSaleName" placeholder="请输入售中姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="售后姓名" prop="afterSaleName">
                            <el-input v-model="form.afterSaleName" placeholder="请输入售后姓名" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="接单姓名" prop="acceptedProgrammerName">
                            <el-input v-model="form.acceptedProgrammerName" placeholder="请输入接单程序员姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="接单时间" prop="acceptTime">
                            <el-date-picker clearable v-model="form.acceptTime" type="date" value-format="yyyy-MM-dd"
                                placeholder="请选择接单时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="信用分" prop="requiredCreditScore">
                            <el-select v-model="form.requiredCreditScore" placeholder="请选择所需最低信用分">
                                <el-option v-for="dict in creditScoreOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="技术等级" prop="requiredSkillLevelId">
                            <el-select v-model="form.requiredSkillLevelId" placeholder="请选择所需最低技术等级">
                                <el-option v-for="level in skillLevelOptions" :key="level.value" :label="level.label"
                                    :value="level.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                </el-row>
                <el-form-item label="退单理由" prop="chargebackReason">
                    <el-input v-model="form.chargebackReason" type="textarea" placeholder="请输入退单理由" />
                </el-form-item>
                <el-form-item label="订单简介" prop="introduce">
                    <el-input v-model="form.introduce" type="textarea" placeholder="请输入内容" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 添加退款对话框 -->
        <el-dialog :title="refundTitle" :visible.sync="refundOpen" width="600px" append-to-body>
            <el-form ref="refundForm" :model="refundForm" :rules="refundRules" label-width="100px">
                <el-form-item label="退款金额" prop="refundAmount">
                    <el-input-number v-model="refundForm.refundAmount" :precision="2" :step="100"
                        placeholder="请输入退款金额" />
                </el-form-item>
                <el-form-item label="退款类型" prop="refundType">
                    <el-select v-model="refundForm.refundType" placeholder="请选择退款类型">
                        <el-option v-for="dict in refundTypeOptions" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="退款原因" prop="refundReason">
                    <el-input v-model="refundForm.refundReason" type="textarea" placeholder="请输入退款原因" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="refundForm.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitRefund">确 定</el-button>
                <el-button @click="cancelRefund">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 文件列表对话框 -->
        <el-dialog :title="fileViewerTitle" :visible.sync="fileViewerOpen" width="600px" append-to-body>
            <el-tabs value="requirements">
                <el-tab-pane label="需求文档" name="requirements">
                    <div v-if="requirementFiles.length > 0" class="file-list-panel">
                        <ul>
                            <li v-for="file in requirementFiles" :key="file.url">
                                <a :href="file.url" target="_blank" class="file-link">
                                    <i class="el-icon-document"></i>
                                    <span>{{ file.name }}</span>
                                    <i class="el-icon-download file-download-icon"></i>
                                </a>
                            </li>
                        </ul>
                    </div>
                    <el-empty v-else description="暂无需求文档"></el-empty>
                </el-tab-pane>
                <el-tab-pane label="订单附件" name="attachments">
                    <div v-if="attachmentFiles.length > 0" class="file-list-panel">
                        <ul>
                            <li v-for="file in attachmentFiles" :key="file.url">
                                <a :href="file.url" target="_blank" class="file-link">
                                    <i class="el-icon-folder-opened"></i>
                                    <span>{{ file.name }}</span>
                                    <i class="el-icon-download file-download-icon"></i>
                                </a>
                            </li>
                        </ul>
                    </div>
                    <el-empty v-else description="暂无订单附件"></el-empty>
                </el-tab-pane>
            </el-tabs>
            <div slot="footer" class="dialog-footer">
                <el-button @click="fileViewerOpen = false">关 闭</el-button>
            </div>
        </el-dialog>

        <!-- 抢单对话框 -->
        <el-dialog :title="preemptTitle" :visible.sync="preemptOpen" width="500px" append-to-body>
            <el-form ref="preemptForm" :model="preemptForm" :rules="preemptRules" label-width="100px">
                <el-form-item label="包单价" prop="biddingAmount">
                    <el-input-number v-model="preemptForm.biddingAmount" :precision="2" :step="10" placeholder="请输入包单价"
                        :min="0" style="width: 100%;"></el-input-number>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitPreempt">确 定</el-button>
                <el-button @click="cancelPreempt">取 消</el-button>
            </div>
        </el-dialog>


    </div>
</template>

<script>
import { wechatTaskList, getOrders, delOrders, addOrders, updateOrders, addRefund, listAllSkillLevels } from "@/api/dashboard/grab"
import { addPreempt, checkPreempt } from "@/api/dashboard/preempt"
import { listOrderRequirements, listOrderAttachments } from "@/api/dashboard/grab"
import { getToken } from "@/utils/auth"

export default {
    name: "Orders",
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 订单主表表格数据
            ordersList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 备注时间范围
            daterangeStartTime: [],
            // 备注时间范围
            daterangeEstimatedEndTime: [],
            // 备注时间范围
            daterangeAcceptTime: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                orderNo: null,
                customerName: null,
                customerPhone: null,
                orderTitle: null,
                isUrgent: null,
                techType: null,
                startTime: null,
                estimatedEndTime: null,
                rewardAmount: null,
                raiseAmount: null,
                workStatus: '1',
                orderStatus: null,
                orderStatusAmount: null,
                inSaleName: null,
                afterSaleName: null,
                acceptedProgrammerName: null,
                acceptTime: null,
                chargebackReason: null,
                storeId: null,
                requiredCreditScore: null,
                requiredSkillLevelId: null,
                keyword: null,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                orderNo: [
                    { required: true, message: "订单号不能为空", trigger: "blur" }
                ],
                customerName: [
                    { required: true, message: "客户姓名不能为空", trigger: "blur" }
                ],
                customerPhone: [
                    { required: true, message: "客户联系方式不能为空", trigger: "blur" }
                ],
                orderTitle: [
                    { required: true, message: "订单标题不能为空", trigger: "blur" }
                ],
                isUrgent: [
                    { required: true, message: "是否加急订单不能为空", trigger: "change" }
                ],
                techType: [
                    { required: true, message: "程序类型不能为空", trigger: "blur" }
                ],
                startTime: [
                    { required: true, message: "程序开始时间不能为空", trigger: "blur" }
                ],
                estimatedEndTime: [
                    { required: true, message: "截止时间不能为空", trigger: "blur" }
                ],
                rewardAmount: [
                    { required: true, message: "订单金额不能为空", trigger: "blur" }
                ],
                orderStatus: [
                    { required: true, message: "订单状态不能为空", trigger: "change" }
                ],
                orderStatusAmount: [
                    { required: true, message: "订单收款状态 不能为空", trigger: "change" }
                ],
                requiredCreditScore: [
                    { required: true, message: "信用分不能为空", trigger: "change" }
                ],
                requiredSkillLevelId: [
                    { required: true, message: "技术等级不能为空", trigger: "change" }
                ],
            },
            // 文件上传相关
            fileViewerOpen: false,
            fileViewerTitle: "",
            currentOrderId: null,
            // 退款对话框
            refundOpen: false,
            refundTitle: "",
            refundForm: {},
            refundRules: {
                refundAmount: [
                    { required: true, message: "退款金额不能为空", trigger: "blur" }
                ],
                refundType: [
                    { required: true, message: "退款类型不能为空", trigger: "change" }
                ],
                refundReason: [
                    { required: true, message: "退款原因不能为空", trigger: "blur" }
                ]
            },
            // 抢单对话框
            preemptOpen: false,
            preemptTitle: "",
            preemptForm: {},
            preemptRules: {
                biddingAmount: [
                    { required: true, message: "包单价不能为空", trigger: "blur" }
                ]
            },
            refundTypeOptions: [
                { label: '程序视频已发放', value: '0' },
                { label: '程序未做完', value: '1' },
                { label: '客户要求退款', value: '2' }
            ],
            requirementFiles: [],
            attachmentFiles: [],
            uploadHeaders: { Authorization: "Bearer " + getToken() },
            // 新增下拉框选项
            orderStatusOptions: [
                { label: '待抢单', value: '0' },
                { label: '重包单', value: '1' },
                { label: '进行中', value: '2' },
                { label: '未过售后期', value: '6' },
                { label: '已完成', value: '5' },
                { label: '服务费', value: '7' },
                { label: '已退单', value: '4' }
                // { label: '外部技术', value: '3' },
            ],
            orderStatusAmountOptions: [
                { label: '定金', value: '0' },
                { label: '首款', value: '1' },
                { label: '中期款', value: '2' },
                { label: '尾款', value: '3' },
                { label: '退款', value: '4' }
            ],
            isUrgentOptions: [
                { label: '加急', value: '1' },
                { label: '不加急', value: '0' }
            ],
            creditScoreOptions: [
                { label: '30', value: 30 }, // Numeric value for credit score
                { label: '50', value: 50 },
                { label: '60', value: 60 },
                { label: '80', value: 80 },
                { label: '100', value: 100 }
            ],
            skillLevelOptions: [],
            techTypeOptions: [{ value: 'JAVA', label: 'JAVA' },
            { value: 'Labview', label: 'Labview' },
            { value: 'Python', label: 'Python' },
            { value: 'Android', 'label': 'Android' },
            { value: '嵌入式', label: '嵌入式' },
            { value: '单片机', label: '单片机' },
            { value: '前端', label: '前端' },
            { value: '小程序', label: '小程序' },
            { value: '开源硬件', label: '开源硬件' },
            { value: 'H5', label: 'H5' },
            { value: 'UI', label: 'UI' },
            { value: 'PHP', label: 'PHP' },
            { value: 'Matlab', label: 'Matlab' },
            { value: 'C#', label: 'C#' },
            { value: 'C++', label: 'C++' },
            { value: 'Solidity', label: 'Solidity' },
            { value: 'DSP', 'label': 'DSP' },
            { value: '论文', label: '论文' },
            { value: 'Hadoop', label: 'Hadoop' },
            { value: 'QT', label: 'QT' },
            { value: 'Go', label: 'Go' }
            ],
            workStatusOptions: [
                { label: '内部技术', value: '0' },
                { label: '外部技术', value: '1' }
            ],

        }
    },
    computed: {
        // 检查是否有删除权限（只有售中主管和admin可以删除）
        canDelete() {
            const roles = this.$store.getters.roles || [];
            return roles.includes('售中主管') || roles.includes('admin');
        }
    },
    created() {
        this.getList()
        this.getSkillLevels()
    },
    methods: {
        /** 查询技术等级列表 */
        getSkillLevels() {
            listAllSkillLevels().then(response => {
                this.skillLevelOptions = response.data.map(item => ({
                    value: item.id,
                    label: `${item.levelCode} - ${item.levelName}`
                }));
            });
        },
        /** 查询订单主表列表 */
        getList() {
            this.loading = true
            this.queryParams.params = {}
            this.queryParams.params["filterNoProgrammer"] = true;
            if (null != this.daterangeStartTime && '' != this.daterangeStartTime) {
                this.queryParams.params["beginStartTime"] = this.daterangeStartTime[0]
                this.queryParams.params["endStartTime"] = this.daterangeStartTime[1]
            }
            if (null != this.daterangeEstimatedEndTime && '' != this.daterangeEstimatedEndTime) {
                this.queryParams.params["beginEstimatedEndTime"] = this.daterangeEstimatedEndTime[0]
                this.queryParams.params["endEstimatedEndTime"] = this.daterangeEstimatedEndTime[1]
            }
            if (null != this.daterangeAcceptTime && '' != this.daterangeAcceptTime) {
                this.queryParams.params["beginAcceptTime"] = this.daterangeAcceptTime[0]
                this.queryParams.params["endAcceptTime"] = this.daterangeAcceptTime[1]
            }
            wechatTaskList(this.queryParams).then(response => {
                this.ordersList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                orderNo: null,
                customerName: null,
                customerPhone: null,
                orderTitle: null,
                isUrgent: null,
                introduce: null,
                techType: null,
                startTime: null,
                estimatedEndTime: null,
                rewardAmount: null,
                raiseAmount: null,
                orderStatus: null,
                orderStatusAmount: null,
                gradRefundId: null,
                inSaleName: null,
                inSaleId: null,
                afterSaleName: null,
                afterSaleId: null,
                acceptedProgrammerName: null,
                acceptedProgrammerId: null,
                acceptTime: null,
                chargebackReason: null,
                storeId: null,
                requiredCreditScore: null,
                requiredSkillLevelId: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                remark: null
            }
            this.resetForm("form")
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeStartTime = []
            this.daterangeEstimatedEndTime = []
            this.daterangeAcceptTime = []
            this.resetForm("queryForm")
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = "新增订单"
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const id = row.id || this.ids
            getOrders(id).then(response => {
                this.form = response.data
                this.open = true
                this.title = "修改订单主表"
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        updateOrders(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功")
                            this.open = false
                            this.getList()
                        })
                    } else {
                        addOrders(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功")
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids
            this.$modal.confirm('是否确认删除订单主表编号为"' + ids + '"的数据项？').then(function () {
                return delOrders(ids)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess("删除成功")
            }).catch(() => { })
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('dashboard/orders/export', {
                ...this.queryParams
            }, `orders_${new Date().getTime()}.xlsx`)
        },
        /** 退款按钮操作 */
        handleRefund(row) {
            this.resetRefundForm();
            this.refundForm.orderId = row.id;
            this.refundOpen = true;
            this.refundTitle = "订单退款 - " + row.orderNo;
        },
        // 取消退款按钮
        cancelRefund() {
            this.refundOpen = false;
            this.resetRefundForm();
        },
        // 退款表单重置
        resetRefundForm() {
            this.refundForm = {
                orderId: null,
                refundAmount: 0.00,
                refundType: null,
                refundReason: null,
                remark: null
            };
            this.resetForm("refundForm");
        },
        /** 提交退款按钮 */
        submitRefund() {
            this.$refs["refundForm"].validate(valid => {
                if (valid) {
                    addRefund(this.refundForm).then(response => {
                        this.$modal.msgSuccess("新增退款成功");
                        this.refundOpen = false;
                        this.getList();
                    });
                }
            });
        },
        /** 文件按钮操作 */
        handleFiles(row) {
            this.currentOrderId = row.gradOrdersId;
            this.fileViewerTitle = "查看文件 - " + row.orderNo;
            this.fileViewerOpen = true;
            this.requirementFiles = [];
            this.attachmentFiles = [];
            this.getFileLists();
        },

        /** 获取文件列表 */
        getFileLists() {
            // 获取需求文档列表
            listOrderRequirements(this.currentOrderId).then(response => {
                if (response.code === 200) {
                    this.requirementFiles = response.data;
                }
            });

            // 获取附件列表
            listOrderAttachments(this.currentOrderId).then(response => {
                if (response.code === 200) {
                    this.attachmentFiles = response.data;
                }
            });
        },

        /** 转换字典标签 */
        selectDictLabel(datas, value) {
            if (value === undefined || value === null || value === '') {
                return "";
            }
            const actions = [];
            Object.keys(datas).map((key) => {
                if (datas[key].value == ('' + value)) {
                    actions.push(datas[key].label);
                    return false;
                }
            })
            return actions.join('');
        },
        getStatusTag(status) {
            const statusOptions = {
                '0': 'info',
                '1': 'success',
                '2': 'warning',
                '3': 'danger',
                '4': 'info',
                '5': 'success',
                '6': 'waring',
                '7': 'danger'
            };
            return statusOptions[status] || 'info';
        },
        /** 订单状态字典翻译 */
        orderStatusFormat(row, column) {
            // ... existing code ...
        },

        // 分享当前页（静态公开页）：将 ordersList 的必要字段打包 base64 放到链接
        handleSharePage() {
            this.generateShareLink();
        },
        /** 抢单按钮操作 */
        handlePreempt(order) {
            this.resetPreemptForm();
            this.preemptForm.gradOrdersId = order.gradOrdersId;
            this.preemptForm.gradOrdersTaskId = order.id;
            this.preemptForm.orderTaskName = order.orderTaskName;
            this.preemptOpen = true;
            this.preemptTitle = "抢单 - " + order.orderNo;
        },
        // 取消抢单按钮
        cancelPreempt() {
            this.preemptOpen = false;
            this.resetPreemptForm();
        },
        // 抢单表单重置
        resetPreemptForm() {
            this.preemptForm = {
                gradOrdersId: null,
                gradOrdersTaskId: null,
                orderTaskName: null,
                biddingAmount: null,
            };
            this.resetForm("preemptForm");
        },
        /** 提交抢单按钮 */
        submitPreempt() {
            this.$refs["preemptForm"].validate(valid => {
                if (valid) {
                    addPreempt(this.preemptForm).then(response => {
                        this.$modal.msgSuccess("抢单成功");
                        this.preemptOpen = false;
                        this.getList();
                    });
                }
            });
        },



        // 生成分享链接
        generateShareLink() {
            // 指向公开路由页面（无需登录）
            const baseHref = (document.querySelector('base') && document.querySelector('base').getAttribute('href')) || '/';
            const base = (baseHref.endsWith('/') ? baseHref.slice(0, -1) : baseHref);
            const origin = window.location.origin;
            const shareLink = `${origin}${base}/share/orders`;

            // 复制链接
            const input = document.createElement('input');
            input.value = shareLink;
            document.body.appendChild(input);
            input.select();
            document.execCommand('copy');
            document.body.removeChild(input);

            this.$message.success('分享链接已复制到剪贴板');
        },


    }
}
</script>

<style scoped>
.ios-style-container {
    background-color: #f0f2f5;
    padding: 20px;
}

.order-card-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    /* Default to 4 columns */
    gap: 20px;
}

/* Responsive adjustments for the grid */
@media (max-width: 1600px) {
    .order-card-grid {
        grid-template-columns: repeat(3, 1fr);
    }
}

@media (max-width: 992px) {
    .order-card-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .order-card-grid {
        grid-template-columns: repeat(1, 1fr);
    }
}

.order-card-wrapper {
    /* Masonry-specific styles are no longer needed. Wrapper is kept for structure. */
}

.order-card {
    background-color: #ffffff;
    border-radius: 12px;
    box-shadow: 0 4px_12px rgba(0, 0, 0, 0.08);
    padding: 20px;
    transition: all 0.3s ease;
    cursor: pointer;
    border: 1px solid transparent;
    /* Reserve space for border */
}

.order-card.is-selected {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(66, 133, 244, 0.2);
    border: 1px solid #4285f4;
}

.order-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    border-bottom: 1px solid #e8e8e8;
    padding-bottom: 15px;
}

.order-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.card-body {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    margin-bottom: 15px;
}

.info-item {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #606266;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.info-item i {
    margin-right: 8px;
    color: #909399;
}

.card-footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 15px;
    border-top: 1px solid #e8e8e8;
}

.full-width-details-panel {
    margin-top: 5px;
    margin-bottom: 20px;
    background-color: #fff;
    border-radius: 12px;
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
    padding: 20px;
    border: 1px solid #000000;
}

.details-content .el-descriptions {
    width: 100%;
}

::v-deep .el-descriptions-item__label.is-bordered-label {
    width: 100px;
    background-color: #f5f7fa;
}

.details-actions {
    display: flex;
    align-items: center;
}

::v-deep .el-descriptions--border .el-descriptions-item__label,
::v-deep .el-descriptions--border .el-descriptions-item__content {
    border: 1px solid #000000;
}

.el-descriptions-item {
    border: 1px solid #000000;
}

.file-list-panel ul {
    list-style-type: none;
    padding: 0;
}

.file-list-panel li {
    margin-bottom: 10px;
}

.file-link {
    display: flex;
    align-items: center;
    padding: 10px 15px;
    border-radius: 8px;
    background-color: #f5f7fa;
    text-decoration: none;
    color: #303133;
    transition: all 0.2s ease-in-out;
    font-size: 14px;
}

.file-link:hover {
    background-color: #ecf5ff;
    color: #409eff;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
}

.file-link i {
    margin-right: 10px;
    font-size: 18px;
}

.file-link span {
    flex-grow: 1;
}

.file-download-icon {
    margin-left: 10px;
    margin-right: 0 !important;
    color: #c0c4cc;
}
</style>
